﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace UberChess.Algorithm
{
    class MinMax
    {
        private enum current { Minimizer, Maximizer };
        private int _currentSearchLevel;
        private List<MinMax> _childNodes;
        public State _currentState { get; set; }
        public double _heuristic { get; private set; }
        State state = new State();

        public MinMax(State currentState, int currentSearchLevel)
        {
            _currentState = currentState;
            _currentSearchLevel = currentSearchLevel;
            _heuristic = Double.PositiveInfinity;
            _childNodes = new List<MinMax>();
            //if (currentSearchLevel > 0)
            //    PopulateChildNodes();
        }

        public double Search(double alpha, double beta)
        {
            if (state.CheckForMate(Side.BLACK))
            {
                _heuristic = double.PositiveInfinity;
                return _heuristic;
            }
            else if (state.CheckForMate(Side.BLACK))
            {
                _heuristic = double.NegativeInfinity;
                return _heuristic;
            }

            else if (state.CheckForDraw())
            {
                _heuristic = 0.0;
                return _heuristic;
            }

            else if (_currentSearchLevel == 0)
            {
                //_heuristic = CalculateStaticEvaluation();
                return _heuristic;
            }
            foreach(var child in _childNodes)
            {
                double V;

                if (alpha < beta)
                {
                    V = child.Search(alpha, beta);
                    
                    alpha = _heuristic = (V > alpha ? V : alpha);
                }
                else
                    break;

                //_heuristic = (nodeHeuristic > _heuristic ? nodeHeuristic : _heuristic);
            }

            return _heuristic;
        }

        public State NextMove()
        {
            _heuristic = Search(double.NegativeInfinity, double.PositiveInfinity);
            return _childNodes.Find(e => e._heuristic == _heuristic)._currentState;
        }
    }
}
